package com.web.contract.controller;

import com.web.common.BaseResult;
import com.web.common.enums.BaseStatus;
import com.web.common.enums.PendingAction;
import com.web.contract.entity.Contract;
import com.web.contract.service.ContractService;
import com.web.pendingList.service.PendingListService;
import com.web.qualification.entity.CustomerQualification;
import com.web.qualification.service.CustomerQualificationService;
import com.web.systemParam.entity.SystemParam;
import com.web.systemParam.service.SystemParamService;
import com.web.transaction.entity.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sound.midi.Soundbank;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wenzhuo
 * @create 2024-06-04 2024/6/4
 */

@RestController
@CrossOrigin
@RequestMapping("/contract")
public class ContractController {


    private static final Logger logger = LoggerFactory.getLogger(ContractController.class);

    @Autowired
    private PendingListService pendingService;

    @Autowired
    private CustomerQualificationService qualificationService;

    @Autowired
    private SystemParamService systemParamService;

    @Autowired
    private ContractService contractService;


    @RequestMapping(value = "/contractList")
    public BaseResult<List<Contract>> getContractList(@ModelAttribute Contract contract){

        List<Contract> contractList = contractService.getContratList(contract);
        return new BaseResult<>(BaseStatus.SUCCESS.getCode(),contractList);
    }

    @PostMapping(value = "/populateAmount")
    public BaseResult populateAmount(@RequestParam("acceptedBooKRate") String acceptedBooKRate,@RequestParam("amount") String amount,@RequestParam("buyOrSell") String buyOrSell){

        BigDecimal resultAmount;
        if(Transaction.TX_BUY.equals(buyOrSell)){
           resultAmount = new BigDecimal(amount).multiply(new BigDecimal(acceptedBooKRate)).setScale(2, RoundingMode.CEILING);
            logger.info("resultAmountBuy: {}",resultAmount);
            return new BaseResult(BaseStatus.SUCCESS.getCode(),resultAmount );
        }

           resultAmount = new BigDecimal(amount).divide(new BigDecimal(acceptedBooKRate),BigDecimal.ROUND_CEILING).setScale(2, RoundingMode.CEILING);
            logger.info("resultAmountSell: {}",resultAmount);
         return new BaseResult(BaseStatus.SUCCESS.getCode(), resultAmount);

    };


    @PostMapping(value = "/createContract")
    public BaseResult createContract(@ModelAttribute Contract contract, @RequestParam("userName") String userName){

        //检查客户号是否允许做预定汇率
        CustomerQualification customerQualification = qualificationService.getCustomerQualificationByCusNo(contract.getCustomerNo());

        if(customerQualification == null){
            return new BaseResult(BaseStatus.INVALID_BOOK_RATE_QUALIFICATION.getCode(),BaseStatus.INVALID_BOOK_RATE_QUALIFICATION.getDesc());
        }

        if(!"Y".equals(customerQualification.getAllowedBookRate())){
            return new BaseResult(BaseStatus.INVALID_BOOK_RATE_ACCESS.getCode(),BaseStatus.INVALID_BOOK_RATE_ACCESS.getDesc());
        }

        //判断SettlementDate是否超过规定的日期
        List<SystemParam> systemParamList = systemParamService.getSystemParamList("CONTRACT_SETTLEMENT_DATE", "INT");
        if(systemParamList.isEmpty()){
            return new BaseResult(BaseStatus.SYSTEM_PARAM_DATA_NOT_EXIST.getCode(),BaseStatus.SYSTEM_PARAM_DATA_NOT_EXIST.getDesc());
        }

        Long settlementDay = Long.valueOf(systemParamList.get(0).getSystemParamValue());
        if(SystemParamService.isAfterDays(contract.getSettlementDate(), settlementDay)){
            return new BaseResult(BaseStatus.INVALID_SETTLEMENT_DATE.getCode(),BaseStatus.INVALID_SETTLEMENT_DATE.getDesc());
        }

        //创建预定汇率进行审批
        return pendingService.addContractPending(PendingAction.ADD.getAction(), Contract.MODULE, userName, contract);

    };

    @RequestMapping(value = "/settlementContract")
    public BaseResult<String> settlementContract(){
        LocalDate now = LocalDate.now();

        //获取状态为NOR的Contract数据
        List<Contract> contractList = contractService.getContratWithNor();

        if(contractList.isEmpty()){
            logger.info("no contract data settlement");
            return new BaseResult<>(BaseStatus.CONTRACT_DATA_NOT_EXIST.getCode(),BaseStatus.CONTRACT_DATA_NOT_EXIST.getDesc());
        }

        ArrayList<Contract> contracts = new ArrayList<>();

        for (Contract contract:contractList){
            System.out.println(contract.getSettlementDate().isEqual(now));
            if(contract.getSettlementDate().isEqual(now)){
                contracts.add(contract);
            }
        }
        //Contract进行结算
        if(!contracts.isEmpty()){
            Integer settlementResult= contractService.settlementContract(contracts);
            if (settlementResult >= 0){
                logger.info("Settlement Contract Success.");
            }
        }else {
            logger.info("No Date Settlement Contract.");
        }

        return new BaseResult<>(BaseStatus.SUCCESS.getCode(),BaseStatus.SUCCESS.getDesc());
    }
}
